package org.idea.qiyu.framework.marketing.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.idea.qiyu.framework.marketing.handler.IMarketingHandler;
import org.idea.qiyu.framework.marketing.model.Marketing;
import org.idea.qiyu.framework.marketing.model.MarketingProduct;
import org.idea.qiyu.framework.marketing.service.IMarketingHandleService;
import org.idea.qiyu.framework.marketing.service.IMarketingProductService;
import org.idea.qiyu.framework.marketing.service.IMarketingService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 营销产品核心处理类
 *
 * @Author linhao
 * @Date created in 6:57 下午 2021/7/23
 */
@Service
@Slf4j
public class MarketingHandleServiceImpl implements IMarketingHandleService {

    @Resource
    private IMarketingProductService marketingProductService;

    @Resource
    private IMarketingService marketingService;

    @Resource
    private ApplicationContext applicationContext;

    /**
     * 营销实际处理模块
     *
     * @param productNo 产品编号
     */
    @Override
    public void coreHandler(Integer productNo) {
        MarketingProduct marketingProduct = marketingProductService.selectByProductNo(productNo);
        if (marketingProduct != null) {
            Integer marketingId = marketingProduct.getMarketingId();
            List<Marketing> marketings = marketingService.selectByMarketingIds(marketingId);
            for (Marketing marketing : marketings) {
                String serviceName = marketing.getMarketingName();
                IMarketingHandler iMarketingHandler = (IMarketingHandler) applicationContext.getBean(serviceName);
                Map<String, Object> paramInput = JSON.parseObject(marketing.getInputVal(), Map.class);
                try {
                    Object result = iMarketingHandler.handlerInput(paramInput);
                    log.info("[coreHandler] marketing is {},result is {}", marketing, result);
                }catch (Exception e){
                    log.error("[coreHandler] marketing is {},error is ", marketing, e);
                }
            }
        }
    }
}
